package com.smsc.headend.connector.netty.encoder;

import cn.hutool.core.util.HexUtil;
import com.smsc.headend.connector.builder.LoggerBuilder;
import com.smsc.headend.connector.netty.NettyConfigHelper;
import com.smsc.headend.connector.utils.LogFileNameUtil;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
public class CosemEncoder extends MessageToByteEncoder<byte[]> {

    @Autowired
    LogFileNameUtil logFileNameUtil;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, byte[] bytes, ByteBuf byteBuf) {
        ComEntity com = channelHandlerContext.channel().attr(NettyConfigHelper.comEntityAttrKey).get();
        if (com == null) {
            LoggerBuilder.getLogger("anno-device", this.getClass()).info("-->:{}", ByteUtils.byteToHexString(bytes));
        } else if (com.getComId() == -1L) {
            LoggerBuilder.getLogger(com.getModuleSn(), this.getClass()).info("-->(anno):{}", ByteUtils.byteToHexString(bytes));
        } else {
            LoggerBuilder.getLogger(logFileNameUtil.getLogFileName(com), this.getClass()).info("-->:{}", ByteUtils.byteToHexString(bytes));
        }
        byteBuf.writeBytes(bytes);
    }
}
